package com.oocl.scan.dao.impl;

import com.arangodb.ArangoCursor;
import com.arangodb.entity.BaseDocument;
import com.arangodb.util.MapBuilder;
import com.oocl.scan.dao.BasicDao;
import com.oocl.scan.dao.ConstantDao;
import com.oocl.scan.model.Constant;
import java.util.Map;

public class ConstantDaoImpl extends BasicDao implements ConstantDao {

  private static final String CONSTANTS = "constants";

  @Override
  public Constant findByFullClassNameAndVariableName(String className, String VariableName) {
    String query = "FOR t IN "+ CONSTANTS +" FILTER t.className == @className FILTER t.variableName == @variableName RETURN t";
    Map<String, Object> bindVars = new MapBuilder().put("className", className).put("variableName", VariableName).get();
    ArangoCursor<Constant> cursor = getDataBase().query(query, bindVars, null, Constant.class);
    Constant object = null;
    while (cursor.hasNext()){
      object = cursor.next();
      break;
    }
    return object;
  }

  @Override
  public void add(Constant constant) {
    Constant result = findByFullClassNameAndVariableName(constant.getClassName(),constant.getVariableName());
    if(result == null){
      BaseDocument document = new BaseDocument();
      document.addAttribute("module", constant.getModule());
      document.addAttribute("className", constant.getClassName());
      document.addAttribute("variableName", constant.getVariableName());
      document.addAttribute("variableValue",constant.getVariableValue());
      getDataBase().collection(CONSTANTS).insertDocument(document);
    }else{
      if(!result.getVariableValue().equals(constant.getVariableValue())){
        result.setVariableValue(constant.getVariableValue());
        getDataBase().collection(CONSTANTS).updateDocument(result.get_key(),result);
      }
    }
  }

  @Override
  public void delete(String key) {
    getDataBase().collection(CONSTANTS).deleteDocument(key);
  }
}
